<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">名称</label>
        <el-input v-model="query.name" clearable placeholder="名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">类型</label>
        <el-input v-model="query.type" clearable placeholder="类型" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <span slot="right">
          <el-switch
            v-model="switchValue"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </span>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="1000px">
        <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="100px">
          <el-form-item label="名称">
            <el-input v-model="form.name" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="类型">
            <el-input v-model="form.type" style="width: 250px;" />
          </el-form-item>
          <div><el-button type="primary" size="mini" @click="addRow()">新增</el-button></div>
          <el-table ref="recordSubs" v-loading="crud.loading" :default-sort="{prop: 'createTime'}" :data="form.recordSubs" size="small" style="width: 100%;">
            <el-table-column align="center" width="200">
              <template slot="header">
                <p>
                  标题
                  <span style="color:red;font-size:16px;">*</span>
                </p>
              </template>
              <template slot-scope="scope" align="center">
                <el-form-item :prop="'recordSubs.' + scope.$index + '.name'">
                  <el-input v-model="scope.row.name" maxlength="50" style="width: 200px;" />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" width="200">
              <template slot="header">
                <p>
                  内容
                  <span style="color:red;font-size:16px;">*</span>
                </p>
              </template>
              <template slot-scope="scope" align="center">
                <el-form-item :prop="'recordSubs.' + scope.$index + '.content'">
                  <el-input v-model="scope.row.content" type="textarea" maxlength="50" style="width: 150px;" />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" width="200">
              <template slot="header">
                <p>
                  备注
                  <span style="color:red;font-size:16px;">*</span>
                </p>
              </template>
              <template slot-scope="scope" align="center">
                <el-form-item :prop="'recordSubs.' + scope.$index + '.remark'">
                  <el-input v-model="scope.row.remark" type="textarea" style="width: 180px;" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="200">
              <template slot="header">
                <p>
                  创建时间
                  <span style="color:red;font-size:16px;">*</span>
                </p>
              </template>
              <template slot-scope="scope" align="center">
                <el-form-item :prop="'recordSubs.' + scope.$index + '.createTime'">
                  <el-date-picker v-model="scope.row.createTime" type="datetime" style="width: 200px;" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-delete" @click.native.prevent="deleteRow(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <!--表格渲染-->
      <label class="el-form-item-label">各类总和：{{ (sumSub/10000)+'万元' }}</label>
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="expand" width="55">
          <template slot-scope="scope">
            <el-table v-loading="detailloading" :data="scope.row.recordSubs" :default-sort="{prop: 'createTime'}" size="small" style="width: 100%;" inline>
              <el-table-column prop="name" label="标题" align="center">
                <template slot-scope="subscope">
                  {{ subscope.row.name }}
                </template>
              </el-table-column>
              <el-table-column prop="content" label="价格" align="center">
                <template slot-scope="subscope">
                  {{ subscope.row.content }}
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" align="center">
                <template slot-scope="subscope">
                  {{ subscope.row.remark }}
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" align="center">
                <template slot-scope="subscope">
                  {{ subscope.row.createTime }}
                </template>
              </el-table-column>

              <el-table-column prop="filePath" label="附件" align="center">
                <template slot-scope="subscope">
                  <span v-if="subscope.row.filePath">
                    <span
                      v-for="(item, i) in subscope.row.filePath.split('|') "
                      :key="i"
                    >
                      <el-image
                        v-if="item!=''"
                        :src="baseApi + item"
                        :preview-src-list="getPreviewSrcList(subscope.row.filePath)"
                        fit="contain"
                        lazy
                        class="el-avatar"
                      >
                        <div slot="error">
                          <i class="el-icon-document" />
                        </div>
                      </el-image>
                    </span>
                  </span>
                  <el-button v-if="switchValue" class="filter-item" type="warning" icon="el-icon-upload" size="mini" @click="uploadPic(subscope.row)" />
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="sum" label="总和">
          <template slot-scope="scope">
            {{ getSumNumber(scope.row) }}
          </template>
        </el-table-column>

        <el-table-column prop="type" label="类型" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column v-if="checkPer(['admin','record:edit','record:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <uploadForm ref="uploadForm" @tell="returnMethod" />

      <pagination />
    </div>
  </div>
</template>

<script>
import uploadForm from './uploadForm'

import crudRecord from '@/api/record'
import crudRecordSub from '@/api/recordSub'

import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = { id: null, recordSubs: [{ name: null }], name: null, type: null, createTime: null, updateTime: null, createBy: null, updateBy: null, projectIdList: [] }
export default {
  name: 'Record',
  components: { uploadForm, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '事件记录', url: 'api/record', idField: 'id', sort: 'createTime,asc', crudMethod: { ...crudRecord }})
  },
  data() {
    return {
      switchValue: false,
      sumSub: 0,
      projectIdList: [],
      picName: null,
      headers: { 'Authorization': getToken() },
      detailloading: false,
      permission: {
        add: ['admin', 'record:add'],
        edit: ['admin', 'record:edit'],
        del: ['admin', 'record:del']
      },
      rules: {
      },
      queryTypeOptions: [
        { key: 'name', display_name: '名称' },
        { key: 'type', display_name: '类型' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    getPreviewSrcList(data) {
      if (data.split('|')) {
        var previewList = []
        var arr = data.substr(0, data.length - 1).split('|')
        for (var i = 0; i < arr.length; i++) {
          previewList.push(this.baseApi + arr[i])
        }
        return previewList
      } else {
        return []
      }
    },

    uploadPic(row, index) {
      console.log(row)
      this.row = row
      if (row.filePath) {
        var arr = row.filePath.split('|')
        for (var i = 0; i < arr.length; i++) {
          if (arr[i]) {
            var array = arr[i].split('/')
            this.$refs.uploadForm.fileList.push({
              'url': this.baseApi + arr[i],
              response: { 'realName': array[3], 'type': array[2] }
            })
          }
        }
      }
      this.$refs.uploadForm.row = row
      this.$refs.uploadForm.dialog = true
    },
    returnMethod(row) {
      crudRecordSub.edit(row).then(res => {
        this.$message('上传成功')
      })
    },
    onBeforeUpload(file) {
      const isIMAGE = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png')
      const isLt1M = file.size / 1024 / 1024 < 100

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.picName = file.name
      return isIMAGE && isLt1M
    },
    handleComplete(response, file, fileList, index) {
      this.form.recordSubs.filePath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.recordSubs.filePath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个图片，本次选择了 ${files.length} 个图片，共选择了 ${files.length + fileList.length} 个图片`)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.sumSub = 0
      crudRecordSub.getSumData().then(res => {
        res.content.forEach(res => {
          if (res.content === undefined || res.content === '') {
            res.content = 0
          }
          this.sumSub += parseInt(res.content)
        })
      })
      return true
    },
    getSumNumber(data) {
      console.log(data)
      var price = null
      data.recordSubs.forEach(res => {
        if (res.content === undefined || res.content === '') {
          res.content = 0
        }
        price += parseInt(res.content)
      })
      return price
    },
    addRow() {
      var temp = {}
      temp.name = null
      this.form.recordSubs.push(temp)
    },
    deleteRow(index, row) {
      if (this.form.recordSubs.length > 1) {
        if (row.id != null) { this.form.projectIdList.push(row.id) }
        this.form.recordSubs.splice(index, 1)
      } else {
        this.$message({
          message: '必须保留一条',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style scoped>
/* ::v-deep .el-upload--picture-card,
::v-deep .el-upload-list__item{
	width: 100px;
	height: 100px;
	line-height: 110px;
} */

</style>
